package com.ultrapower.ctool.utils;

/**
 * Created by club on 2017/5/10.
 */

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import com.google.gson.Gson;
import com.ultrapower.ctool.AppContext;
import com.ultrapower.ctool.ConfUtils;
import com.ultrapower.ctool.core.CustomApplication;
import com.ultrapower.ctool.model.RegisterRolePirVO;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * @author lai_zs
 * @date：2012-2-16 下午4:16:02
 */
public class DBHelper extends SQLiteOpenHelper {
    private static final int DATABASE_VERSION = 1;
    private static final String DATABASE_NAME = "autoComplete.db";
    private CustomApplication application;
    //private OkHttpClient client = new OkHttpClient();
    private Gson gson = new Gson();
    // 根据name自动查询
    public static final String NAME = "cn";
    public static final String ID = "_id";

    public DBHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        application = (CustomApplication) CustomApplication.getInstance();
        try {
            OkHttpClient client = new OkHttpClient();
            String sqlString = "create table district (_id varchat(20) not null,cn varchat(50) not null on conflict fail)";
            db.execSQL(sqlString);
            System.out.println(sqlString);
            RequestBody requestBody = new FormBody.Builder()
                    .add("field", "xid")
                    .add("code", "c_pt_user")
                    .add("userId", String.valueOf(application.getLoginUser().getLogin_id()))
                    .build();
            Request request = new Request.Builder().url(ConfUtils.SERVICE_URL + "widget/findJson").post(requestBody).build();
            Response response = null;

            response = client.newCall(request).execute();

            if (response.isSuccessful()) {//成功
                String result = response.body().string();
                Map<String, Object> resultMap = gson.fromJson(result, Map.class);
                // 初始数据库表
                List<Map<String, Object>> list = (List<Map<String, Object>>) resultMap.get("rows");
                for (Map<String, Object> li : list) {
                    db.execSQL("INSERT INTO district  values(?,?)", new Object[]{li.get("xid"), li.get("aname")});
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
        // do nothing here
    }

    /**
     * 根据输入内容模糊查询
     *
     * @param name
     * @return
     */

    public Cursor query(String name) {
        //System.out.println(name);
        if (name != null) {
            SQLiteDatabase db = this.getReadableDatabase();
            return db.rawQuery("select _id,cn from district where cn like '%" + name + "%' limit 10", null);
        }
        return null;
    }

    public String queryBycn(String cn) {
        System.out.println(cn);
        if (cn != null) {
            SQLiteDatabase db = this.getReadableDatabase();
            Cursor cu = db.rawQuery("select _id,cn from district where cn='" + cn + "'", null);
            if (cu.getCount() == 1) {
                while (cu.moveToNext()) {
                    System.out.println(cu.getColumnIndex("_id"));
                    String re=cu.getString(cu.getColumnIndex("_id"));
                    cu.close();
                    return re;
                }
                cu.close();

            }
            db.close();

        }
        return "";
    }

}

